const http = require('http');
const fs = require('fs');
const superagent = require('superagent');
const cheerio = require('cheerio');
const moment = require('moment');
const HttpClient = require("baidu-aip-sdk").HttpClient
const AipOcrClient = require("baidu-aip-sdk").ocr;
const config = require('./config')

class Signer {
  constructor() {
    HttpClient.setRequestOptions({proxy: config.PROXY, rejectUnauthorized: false});
    this.client = new AipOcrClient(config.APP_ID, config.API_KEY, config.SECRET_KEY);
  }
  async start() {
    const [$, cookie] = await this._requestLoginPage();
    const rnCode = await this._getRnCode(cookie);
    await this._login($, cookie, rnCode, config.USERNAME, config.PASSWORD);
    const $_attendance = await this._requestAttendancePage(cookie);
    await this._attendance(cookie, $_attendance('[name="currentempoid"]')[0].attribs.value)
    console.log('sign succ ' + moment().format('YYYY-MM-DD HH:mm:ss'));
  }

  _requestLoginPage() {
    return new Promise((reslove, reject) => {
      superagent.get(config.URL_INDEX).set({
        "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36",
        "Content-Type":"application/x-www-form-urlencoded"
      }).end((err, res) => {
        if(!err) {
          reslove([cheerio.load(res.text), res.headers["set-cookie"]]);
        } else {
          reject('连接失败')
        }
      })
    })
  }
  _getRnCode(cookie) {
    return new Promise((reslove, reject) => {
      const request = http.get({ 
        host: config.URL_HOST,
        path: config.URL_PATH,
        port: config.URL_PORT,
        headers: {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
            "accept-encoding": "gzip,deflate",
            "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36",
            "Cookie": cookie
        }
      });
      request.on('response', response=>{
        let output = fs.createWriteStream(`./${config.USERNAME}code.jpg`);
        response.pipe(output);
        output.on('finish', () => {
          const image = fs.readFileSync(`./${config.USERNAME}code.jpg`).toString("base64");
          this.client.generalBasic(image).then(result => {
            reslove(result.words_result[0].words)
          })
        })
      })
    })
  }
  _login($, cookie, rnCode, username, password) {
    return new Promise((reslove, reject) => {
      let formData = {}
      const input = $("input")
      formData[input[0].attribs.name] = input[0].attribs.value
      formData[input[1].attribs.name] = input[1].attribs.value
      formData[input[2].attribs.name] = input[2].attribs.value
      formData[input[3].attribs.name] = input[3].attribs.value
      formData[input[4].attribs.name] = username
      formData[input[5].attribs.name] = password
      formData[input[6].attribs.name] = rnCode
      superagent.post(config.URL_LOGIN).send(formData).set({
        "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36",
        "Content-Type":"application/x-www-form-urlencoded",
        "Cookie": cookie
      }).end((err, res) => {
        reslove(cheerio.load(res.text)(".error").text())
      })
    })
  }
  _requestAttendancePage(cookie) {
    return new Promise((reslove, reject) => {
      superagent.get(config.URL_ATTENDANCE).set({
        "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36",
        "Content-Type":"application/x-www-form-urlencoded",
        "Cookie": cookie
      }).end((err, res) => {
        reslove(cheerio.load(res.text));
      })
    })
  }
  _attendance(cookie, currentempoid) {
    return new Promise((reslove, reject) => {
      let formData = {}
      formData['currentempoid'] = currentempoid
      formData['browser'] = 'Chrome'
      superagent.post(config.URL_RECORD).send(formData).set({
        "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36",
        "Content-Type":"application/x-www-form-urlencoded",
        "Cookie": cookie
      }).end((err, res) => {
        const $ = cheerio.load(res.text);
        let arr = []
        $('.kq-message-table tbody tr').map((i, n) => {
          arr.push($(n).find('td').eq(3).text() + ' ' + $(n).find('td').eq(4).text())
        })
        reslove(arr)
      })
    })
  }
}

module.exports = Signer;
